<template>
  <div class="app-container">
    <info-page-container>
      <!--表单放入info-page-container组件的body插槽-->
      <template slot="body">
        <el-scrollbar>
          <el-form :rules="rules" :model="form" ref="form" size="small"
                   label-width="80px">
            <!--检查名称输入-->
            <el-form-item class="column-item" label="检查名称" prop="inspectName">
              <el-input
                  v-model="form.inspectName"
                  placeholder="请输入检查名称"
                  clearable
              >
              </el-input>
            </el-form-item>

            <div class="row-item flex-row">
              <!--检查年份输入-->
              <el-form-item class="column-item half-item" label="检查年份" prop="inspectYear">
                <el-date-picker
                    v-model="form.inspectYear"
                    align="right"
                    type="year"
                    value-format="yyyy"
                    placeholder="选择年">
                </el-date-picker>
              </el-form-item>

              <!--检查层级输入-->
              <el-form-item class="column-item half-item" label="检查层级" prop="inspectLevel">
                <el-select v-model="form.inspectLevel" placeholder="请输入检查层级" clearable>
                  <!--使用循环的方式为下拉列表中添加字典中的数据-->
                  <el-option
                      v-for="dict in dict.type.defect_inspect_level"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>

            </div>


            <!--牵头部门输入-->
            <el-form-item class="column-item" label="牵头部门" prop="leadDepartment">
              <el-input
                  v-model="form.leadDepartment"
                  placeholder="请输入牵头部门"
                  clearable
              >
              </el-input>
            </el-form-item>


            <!--检查内容输入-->
            <el-form-item class="column-item" label="检查内容" prop="inspectContent">
              <el-input type="textarea" v-model="form.inspectContent" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <!--计划完成时间输入-->
            <el-form-item class="column-item" label="计划完成时间" required>
              <el-form-item prop="planCompleteTime">
                <el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                                v-model="form.planCompleteTime" clearable style="width: 100%; "></el-date-picker>
              </el-form-item>
            </el-form-item>


            <!--检查批次输入-->
            <el-form-item class="column-item" label="检查批次" prop="inspectBatch">
              <el-input
                  v-model="form.inspectBatch"
                  placeholder="请输入检查批次"
                  clearable
              >
              </el-input>
            </el-form-item>
            <!--检查目标-->
            <el-form-item class="column-item" label="检查目标" prop="orgList">
              <choose-org v-model="form.orgList"></choose-org>
            </el-form-item>


            <!--附件上传-->
            <el-form-item class="column-item annex-box" label="文件列表" prop="fileIds">
              <template slot="label">
                文件列表
                <el-button class="file-upload-bt" icon="el-icon-refresh" size="mini"
                           @click="upload">上传文件
                </el-button>
              </template>
              <show-file-list :file-list="fileList" @delFile="delFile"></show-file-list>
            </el-form-item>
          </el-form>

        </el-scrollbar>
      </template>
      <!--功能按钮放入info-page-container组件的footer插槽-->
      <template slot="footer">
        <!--此处要用form.id来判断页面是从新增进来的还是修改进来的，从而确定是否要有删除按钮-->
        <el-button v-if="form.id != null" @click="removeInspect" icon="el-icon-delete" size="mini" type="danger">删除
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="saveDraft">保存草稿</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">创建</el-button>
      </template>
    </info-page-container>
  </div>
</template>

<script>
//引入文件上传模块
import {UploadFileObj} from "@/utils/uploadFile";
import ShowFileList from "@/components/ShowFileList/index.vue";
import {isArr} from "@/utils/arrayUtil";
import guid from "@/utils/guid";
//引入接口
import {
  addDefectInspect,
  createDefectInspect, delDefectInspect,
  getDefectInspectInfoById, updateAndStartDefectInspect,
  updateDefectInspect
} from "@/api/securityCheck/ztDefectInspect";
import ChooseOrg from "@/views/components/ChooseOrg/index.vue";

export default {
  name: "ztDefectInspect_info",
  dicts: ['defect_inspect_level'],  //引入字典defect_inspect_level

  components: {
    ChooseOrg,
    ShowFileList  //注册子组件
  },
  data() {
    return {
      uid: `file_${guid()}`,  //用来获取当前页面对应路由
      form: {
        id: null,
        fileIds: [],
        inspectBatch: null,
        inspectContent: null,
        inspectLevel: null,
        inspectName: null,
        inspectYear: null,
        leadDepartment: null,
        orgList: [],
        planCompleteTime: null
      },
      // 表单校验
      rules: {
        inspectBatch: [
          {required: true, message: "检查批次不能为空", trigger: "blur"} //光标离开此文本框时内容不能为空
        ],
      },
    }
  },
  computed: {
    fileList() {
      let res = this.$store.state.temporaryFile.temporaryFileList
      return isArr(res) && res.some(item => item.uid == this.uid) ? res.find(item => item.uid == this.uid).fileList : []
    }
  },
  watch: {
    fileList(val) {
      this.form.fileIds = isArr(val) ? val.map(file => file.fileId) : [];
    }
  },
  methods: {
    //上传文件按钮回调函数
    upload() {
      let uploadObj = UploadFileObj.getInstance();
      uploadObj.uploadFile('temporaryFile/addDoc', {uid: this.uid})
    },
    //删除附件列表中附件回调函数
    delFile(item) {
      let owner = this
      let {uid} = this
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
        let {fileId, fileName,} = item
        owner.$store.dispatch("temporaryFile/removeProjectDoc", {uid, fileId, fileName,},).then(() => {
          owner.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      })
    },
    //删除按钮回调函数
    removeInspect() {
      let owner = this; //将当前vc赋值给owner
      //调用接口发送请求
      this.$modal.confirm('是否确认删除该数据项？').then(() => {
        //调用接口发送请求
        delDefectInspect(this.form.id).then((res) => {
          //调用成功消息函数
          owner.$modal.msgSuccess("删除成功");
          //调用返回上一层函数
          owner.saveFinish()
        }, (err) => {
          //调用失败消息函数
          owner.$modal.msgError(`删除失败${err}`);
        })
      })
    },
    //保存草稿按钮回调函数
    saveDraft() {
      let owner = this
      //获取ref属性值为form的组件对象并调用其validate函数进行表单校验
      this.$refs["form"].validate(valid => {
        //判断表单校验是否成功，成功时valid为true
        if (valid) {
          this.startLoading('正在加载....')
          //通过判断数据中的主键值是否为空，为空时新增，不为空时为修改
          if (this.form.id != null) {
            //调用修改专题检查接口参数为当前页面对应的数据
            updateDefectInspect(this.form).then(response => {
              //调用成功消息函数
              owner.$modal.msgSuccess('保存草稿成功')
              //调用返回上级路由函数，使页面从修改页面返回到列表页面
              owner.saveFinish()
            }).finally(() =>{
              owner.endLoading()
            });
          } else {
            //当主键为空时调用新增专题检查接口参数为当前页面对应的data中的数据
            addDefectInspect(this.form).then(res => {
              owner.$modal.msgSuccess('保存草稿成功')
              owner.saveFinish()
            }).finally(() =>{
              owner.endLoading()
            })
          }
        }
      });
    },
    //创建按钮回调函数
    handleAdd() {
      let owner = this
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.startLoading('正在加载....')
          if (this.form.id != null) {
            updateAndStartDefectInspect(this.form).then(response => {
              owner.$modal.msgSuccess('新增成功')
              owner.saveFinish()
            }).finally(() =>{
              owner.endLoading()
            });
          } else {
            createDefectInspect(this.form).then(res => {
              owner.$modal.msgSuccess('新增成功')
              owner.saveFinish()  //返回上一级页面
            }).finally(() =>{
              owner.endLoading()
            })
          }
        }
      });
    },
    //此方法用于操作路由返回上一级
    saveFinish() {
      this.$router.back(-1)
    },

    //检查目标获取光标回调函数
    chooseTarget() {

    },
    //详情查看回调函数
    getInfoData() {
      //此处开启一个加载动画，避免详情渲染在页面上前用户对数据进行操作
      this.startLoading('正在加载....')
      let owner = this
      //调用查询专题检查详情接口
      getDefectInspectInfoById(this.form.id).then(res => {
        let {data: {fileVoList}, data} = res;  //解构

        owner.$store.dispatch('temporaryFile/addDocList', {uid: this.uid, fileList: fileVoList})
        owner.form = data
      }).finally(() => {
        owner.endLoading()  //结束加载动画
      })
    }
  },

  //此周期函数用于打开详情页面时从路由中获取id，并将其赋值给form的id属性
  created() {
    if (this.$route.query != null && this.$route.query?.id != null) {
      this.form.id = this.$route.query.id //给form对象的id属性赋值
      this.getInfoData()  //调用详情查看回调函数
    }
  }
}
</script>

<style lang="scss" scoped>
.annex-box {
  margin-top: 20px; //用于单独设置上传文件按钮与上方元素间距
}
</style>
